<?php
/**
 * 汇友科技
 * @copyright (c) 2017 http://www.huiyou365.net All rights reserved.
 * @author: Creatint <creatint@163.com>
 */

namespace Admin\Model;

use Common\Model\Model;
use Think\Page;

class ArticleModel extends Model{

    protected $_validate = array(
        array('name', '/^[a-zA-Z]\w{0,39}$/', '文档标识不合法', self::VALUE_VALIDATE, 'regex', self::MODEL_BOTH),
        array('name', 'checkName', '标识已经存在', self::VALUE_VALIDATE, 'callback', self::MODEL_BOTH),
        array('title', 'require', '标题不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
        array('title', '1,80', '标题长度不能超过80个字符', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
    );

    protected $_auto = array(
        array('position', 'getPosition', self::MODEL_BOTH, 'callback'),
        array('created_at', NOW_TIME, self::MODEL_INSERT),
        array('updated_at', NOW_TIME, self::MODEL_BOTH),
    );

    protected $page = null;

    /**
     * 添加配置项.
     *
     * @param $data
     * @return bool
     */
    public function update($data){
        if( !$data ) {
            $data = $_POST;
        }

        // 无status则默认为1
        $data['status'] != 1 && $data['status'] != 0 && $data['status'] = 1;

        // 若有id，取数据库中数据，相同值的字段销毁
//        if ( $data['id']>0 ) {
//            $info = $this->find($data['id']);
//            foreach( $data as $k=>$v ) {
//                if ( isset($info[$k]) && $info[$k] == $v && $k != 'id') {
//                    unset($data[$k]);
//                }
//            }
//        }

        // name字段大写
//        isset($data['name']) && $data['name'] = strtoupper($data['name']);

        // 程序出口值,0:失败, >1:成功, 以位运算的或运算来修改其值
        $res = 1;

        // 验证数据,验证失败则 res = 0
        $res &= (bool)($data = $this->create($data)) ;

        // 如果id存在,则更新,保存失败则 res = 0
        $res && $data['id'] && ($res &= (bool)$this->save($data));

        // 如果id不存在,则新增,新增成功则 res = id（返回ID）
        $res && !$data['id'] && ($id = $this->add($data)) && ($res = $id);

        // 程序出口
        return $res;
    }


    public function remove($id){
        if ( !$id ) {
            $this->error = '待删除项为空';
            return false;
        }
        $map = [
            'id'=>[
                'IN',
                $id
            ]
        ];
        if ( $this->where($map)->delete() ) {
            S('DB_CONFIG', null);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检查标识是否已存在(只需在同一根节点下不重复)
     * @param string $name
     * @return true无重复，false已存在
     * @author huajie <banhuajie@163.com>
     */
    protected function checkName(){
        $name        = I('post.name');
        $category_id = I('post.category_id', 0);
        $id          = I('post.id', 0);

        $map = array('name' => $name, 'id' => array('neq', $id), 'status' => array('neq', -1));

        $category = get_category($category_id);
        if ($category['pid'] == 0) {
            $map['category_id'] = $category_id;
        } else {
            $parent             = get_parent_category($category['id']);
            $root               = array_shift($parent);
            $map['category_id'] = array('in', D("Category")->getChildrenId($root['id']));
        }

        $res = $this->where($map)->getField('id');
        if ($res) {
            return false;
        }
        return true;
    }

    /**
     * 生成推荐位的值
     * @return number 推荐位
     * @author huajie <banhuajie@163.com>
     */
    protected function getPosition(){
        $position = I('post.position');
        if(!is_array($position)){
            return 0;
        }else{
            $pos = 0;
            foreach ($position as $key=>$value){
                $pos += $value;		//将各个推荐位的值相加
            }
            return $pos;
        }
    }

    public function getPage(){
        return $this->page;
    }

}